<template>
  <AntdGenerateForm
    ref="generateFormRef"
    :is-show="state.previewVisible"
    :data="state.widgetForm"
    :disabled="props.disabled"
    :disabled-field-codes="disabledFieldCodes || []"
    :remote-replace="remoteReplace"
    :query-value-flag="queryValueFlag === 1"
    :preset-values="presetValues"
    :approval-permission="approvalPermission"
    :no-border="noBorder"
    :default-retract="defaultRetract"
    @change="itemValueChange"
  />
</template>
<script lang="ts" setup>
import AntdGenerateForm from './AntdGenerateForm.vue'
import { reactive, ref, onMounted, watch, computed } from 'vue'
import { cloneDeep } from 'lodash'
import { setVal, attrs, antd, getDatePickerFormat } from './config'
import { fieldTypeOpstion } from './config/enum'
import { formDetail, formDetailApp } from '@@/api/form/index'
import { useUserStore } from '@/store/modules/user'

const props = defineProps<{
  formId: string
  // 1: 平台层级; 2: 组织层级; 3: 业务层级; 4: 应用
  formBusinessLevel?: number
  queryValueFlag?: number
  disabled?: boolean
  // 表单预置值
  presetValues?: object
  // 替换参数值
  replaceVal?: any
  // 需要禁用的字段
  disabledFieldCodes?: any[]
  approvalPermission?: boolean
  noBorder?: boolean // card是否不使用border（适用于任务弹窗内部，不带border和padding的）
  defaultRetract?: boolean
}>()

const state = reactive({
  previewVisible: false,
  widgetForm: cloneDeep(antd.widgetForm)
})
const generateFormRef = ref()

onMounted(() => {
  review()
})

watch(
  () => props.formId,
  () => {
    review()
  }
)

const emits = defineEmits(['itemValueChange', 'finishLoading'])

const review = () => {
  state.widgetForm.list = []
  state.previewVisible = false
  let fn: any = null
  const params: any = {
    formId: props.formId
  }
  if (props.formBusinessLevel === 4) {
    fn = formDetailApp
    params.queryValueFlag = props.queryValueFlag
  } else {
    fn = formDetail
  }
  fn(params).then((res: any) => {
    const tempConfig = cloneDeep(res)
    delete tempConfig.fieldList
    state.widgetForm.config = {
      ...tempConfig
    }
    convertFieldListToShow(res.fieldList)
    state.previewVisible = true
    finishLoading()
  })
}

/**
 * 通知父页面完成数据加载
 */
const finishLoading = () => {
  emits('finishLoading')
}

const convertFieldListToShow = (fieldArr) => {
  fieldArr.forEach((field) => {
    const typeObj = fieldTypeOpstion.find((type) => type.value === field.fieldType)
    if (typeObj) {
      const componentObj = antd[typeObj.type].find((item) => item.type === typeObj.code)
      if (componentObj) {
        convertFieldToShow(field, componentObj)
      }
    }
  })
}

const convertFieldToShow = (remoteField, localComponent) => {
  const tempItem = cloneDeep(localComponent)
  for (const key in remoteField) {
    const fieldAttr = attrs.find((item) => item.remote === key)
    if (fieldAttr) {
      if (key === 'dateFormat') {
        setVal(tempItem, fieldAttr.local, getDatePickerFormat(remoteField.dateType, remoteField.dateFormat).value)
      } else {
        setVal(tempItem, fieldAttr.local, key === 'requiredFlag' ? !!remoteField[key] : remoteField[key])
      }
    }
  }
  console.log(tempItem, '*----tempItem')
  state.widgetForm.list.push(tempItem)
}

const getData = (isValidate = true) => {
  return new Promise((resolve, reject) => {
    generateFormRef.value
      .getData(isValidate)
      .then((res: any) => {
        resolve(cloneDeep(res))
      })
      .catch((err: any) => {
        reject(err)
      })
  })
}

const getBusinessData = (isValidate = true) => {
  return new Promise((resolve, reject) => {
    generateFormRef.value
      .getBusinessData(isValidate)
      .then((res: any) => {
        resolve(res)
      })
      .catch((err: any) => {
        reject(err)
      })
  })
}

const getFormFieldValues = (isValidate = true) => {
  return new Promise((resolve, reject) => {
    generateFormRef.value
      .getFormFieldValues(isValidate)
      .then((res: any) => {
        resolve(res)
      })
      .catch((err: any) => {
        reject(err)
      })
  })
}

const userStore = useUserStore()

const remoteReplace = computed(() => {
  let orgId
  if (props.replaceVal && props.replaceVal.orgId) {
    orgId = props.replaceVal.orgId
  } else {
    orgId = userStore.getOrgId || '0'
  }
  let projectId
  if (props.replaceVal && props.replaceVal.projectId) {
    projectId = props.replaceVal.projectId
  } else {
    projectId = sessionStorage.getItem('__projectId') || ''
  }
  return { projectId, orgId }
})

const itemValueChange = (data) => {
  emits('itemValueChange', data)
}

defineExpose({
  getData,
  getBusinessData,
  getFormFieldValues
})
</script>
<style lang="less"></style>
